package com.nulldev.util.data.Arrays.misc;

import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import com.nulldev.util.data.Variables;

public class RoundRobin<T> implements Iterable<T> {
	private final List<T> coll;

	public RoundRobin(List<T> coll) {
		this.coll = Variables.checkNotNull(coll);
	}

	public Iterator<T> iterator() {
		return new Iterator<T>() {
			private final AtomicInteger index = new AtomicInteger();

			@Override
			public boolean hasNext() {
				return true;
			}

			@Override
			public T next() {
				try {
					if (index.get() >= coll.size())
						index.set(0);
					final T ret = coll.get(index.get());
					index.lazySet((index.get() + 1) % coll.size());
					return ret;
				} catch (IndexOutOfBoundsException ex) {
					index.lazySet(0);
					return this.next();
				}
			}

			@Override
			public void remove() {
			}

		};
	}
}
